package com.ljpz.web.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljpz.web.bean.Cart;
import com.ljpz.common.utils.CookieUtils;
import com.ljpz.web.bean.OrderItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by liujunchen on 2017/1/10.
 */
@Service
public class CartCookieService {
    private   static  final  String COOKIE_NAME="TT_CART";
    private   static  final  Integer  COOKIE_TIME=60*60*24*30*12;
    private  static   final ObjectMapper MAPPER= new ObjectMapper();
    public void delete(List<OrderItem> orderItems , HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Cart> carts= queryCartlist(request);
        for (OrderItem  orderItem:orderItems){
            /*迭代删除回报ConcurrentModificationException异常
            for (Cart cart : carts){
                if (cart.getItemId().longValue()==orderItem.getItemId().longValue())
                    carts.iterator().remove() ;
            }*/
            for (Iterator<Cart> it =carts.iterator();it.hasNext();){
                Cart cart = it.next();
                if (cart.getItemId().longValue()==orderItem.getItemId().longValue()){
                    it.remove();
                }
            }
        }
        //将购物车列表数据写入到cookie中
        CookieUtils.setCookie(request,
                response,COOKIE_NAME,MAPPER.writeValueAsString(carts),COOKIE_TIME,true);
    }
    public List<Cart> queryCartlist(HttpServletRequest request) throws  Exception {
        String jsonData = CookieUtils.getCookieValue(request,COOKIE_NAME,true)  ;
        List<Cart> carts =null ;
        if(StringUtils.isEmpty(jsonData)){
            carts=new ArrayList<Cart>() ;
        }else {
            //反序列化
            carts=MAPPER.readValue(jsonData,
                    MAPPER.getTypeFactory().constructCollectionType(List.class,Cart.class));
        }
        //TODO  排序

        return  carts;
    }
}
